package com.xstudio.pvzreborn.gui.container;

import com.xstudio.pvzreborn.block.BlockNames;
import com.xstudio.pvzreborn.block.entity.BlockEntitySeedPacketCreator;
import com.xstudio.pvzreborn.gui.container.dataslot.IntDataSlot;
import com.xstudio.pvzreborn.gui.container.dataslot.SunshineDataSlot;
import com.xstudio.pvzreborn.handle.OutputOnlySlotHandler;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import org.jetbrains.annotations.NotNull;

public class ContainerSeedPacketCreator extends BaseContainer<BlockEntitySeedPacketCreator> {

	public ContainerSeedPacketCreator(int windowId, Inventory playerInv, BlockPos pos) {
		super(windowId, ContainerManager.getMenuType(BlockNames.SEED_PACKET_CREATOR), playerInv, pos);
	}

	public ContainerSeedPacketCreator(int windowId, Inventory playerInv, FriendlyByteBuf buf) {
		this(windowId, playerInv, buf.readBlockPos());
	}

	@Override
	public void init() {
		addItemSlot();
		addDataSlot(new SunshineDataSlot(getSunshineEnergy()));
		addDataSlot(new IntDataSlot(blockEntity::getProcessTime, blockEntity::setProcessTime));
	}

	@NotNull
	@Override
	public ItemStack quickMoveStack(@NotNull Player pPlayer, int pIndex) {
		ItemStack itemStack = ItemStack.EMPTY;
		Slot slot = this.slots.get(pIndex);
		if (slot.hasItem()) {
			ItemStack stack = slot.getItem();
			itemStack = stack.copy();
			if (pIndex >= 0 && pIndex < 6) {
				if (!this.moveItemStackTo(stack, 6, 42, false)) {
					return ItemStack.EMPTY;
				}
				slot.onQuickCraft(stack, itemStack);
			} else if (!moveItemStackTo(stack, 0, 5, stack.is(Items.PAPER))) {
				return ItemStack.EMPTY;
			}
			slot.onTake(player, stack);
		}
		return itemStack;
	}

	@Override
	protected void addItemSlot() {
		IItemHandler input = getHandler(Direction.SOUTH);
		for (int i = 0; i < 4; i++) {
			addSlot(new SlotItemHandler(input, i, 6, 3 * (2 + 6 * i)));
		}
		addSlot(new SlotItemHandler(getHandler(Direction.UP), 0, 40, 33));
		addSlot(new OutputOnlySlotHandler(getHandler(Direction.DOWN), 0, 120, 33));
	}

}
